using System;
using System.IO;
using LS.UnityExtensions;
using UnityEngine;

namespace LS.Digitize
{
    public sealed class TypeSerializer: CompoundSerializer<Type>
    {
        public TypeSerializer() : base(typeof(Type),typeof(string))
        {
            
        }

        public override void WriteData(IWriter writer, Type obj)
        {
            ISerializer subSerializer = SubSerializer;
            if (subSerializer is PrimitiveSerializer<string> ps)
                ps.WriteData(writer, LSReflection.GetTypeString(obj));
            else
                subSerializer.Write(writer, LSReflection.GetTypeString(obj));
        }

        public override Type ReadData(IReader reader)
        {
            ISerializer subSerializer = SubSerializer;
            if (subSerializer is PrimitiveSerializer<string> ps)
                
                return LSReflection.GetType(ps.ReadData(reader));
            else
                return LSReflection.GetType((string)subSerializer.Read(reader));
            
        }
        
        public override void ReadInto(IReader reader, ref Type obj)
        {
            obj = ReadData(reader);
        }
    }
}